export default {
	websokect: null,
	globalUserId: '',
	limitFlag: false,
	listKey: [],
	list: [],
	curUser: {},
	chatMessage: [],
	offlineMessage: [],
	originFace: ["[f0]", "[f1]", "[f2]", "[f3]", "[f4]", "[f5]", "[f6]", "[f7]", "[f8]", "[f9]", "[f10]",
		"[f11]",
		"[f12]",
		"[f13]", "[f14]", "[f15]", "[f16]", "[f17]", "[f18]", "[f19]",
		"[f20]", "[f21]", "[f22]", "[f23]", "[f24]", "[f25]", "[f26]", "[f27]", "[f28]", "[f29]",
		"[f30]", "[f31]", "[f32]", "[f33]", "[f34]", "[f35]", "[f36]", "[f37]", "[f38]", "[f39]",
		"[f40]", "[f41]", "[f42]", "[f43]", "[f44]", "[f45]", "[f46]", "[f47]", "[f48]", "[f49]",
		"[f50]", "[f51]", "[f52]", "[f53]", "[f54]", "[f55]", "[f56]", "[f57]", "[f58]", "[f59]",
		"[f60]", "[f61]", "[f62]", "[f63]", "[f64]", "[f65]", "[f66]", "[f67]", "[f68]", "[f69]",
		"[f70]", "[f71]"
	],
	faceList: ["/static/face/f0.gif", "/static/face/f1.gif", "/static/face/f2.gif", "/static/face/f3.gif",
		"/static/face/f4.gif", "/static/face/f5.gif", "/static/face/f6.gif", "/static/face/f7.gif",
		"/static/face/f8.gif", "/static/face/f9.gif", "/static/face/f10.gif", "/static/face/f11.gif", "/static/face/f12.gif",
		"/static/face/f13.gif", "/static/face/f14.gif", "/static/face/f15.gif", "/static/face/f16.gif",
		"/static/face/f17.gif", "/static/face/f18.gif", "/static/face/f19.gif",
		"/static/face/f20.gif", "/static/face/f21.gif", "/static/face/f22.gif", "/static/face/f23.gif",
		"/static/face/f24.gif", "/static/face/f25.gif", "/static/face/f26.gif", "/static/face/f27.gif",
		"/static/face/f28.gif", "/static/face/f29.gif",
		"/static/face/f30.gif", "/static/face/f31.gif", "/static/face/f32.gif", "/static/face/f33.gif",
		"/static/face/f34.gif", "/static/face/f35.gif", "/static/face/f36.gif", "/static/face/f37.gif",
		"/static/face/f38.gif", "/static/face/f39.gif",
		"/static/face/f40.gif", "/static/face/f41.gif", "/static/face/f42.gif", "/static/face/f43.gif",
		"/static/face/f44.gif", "/static/face/f45.gif", "/static/face/f46.gif", "/static/face/f47.gif",
		"/static/face/f48.gif", "/static/face/f49.gif",
		"/static/face/f50.gif", "/static/face/f51.gif", "/static/face/f52.gif", "/static/face/f53.gif",
		"/static/face/f54.gif", "/static/face/f55.gif", "/static/face/f56.gif", "/static/face/f57.gif",
		"/static/face/f58.gif", "/static/face/f59.gif",
		"/static/face/f60.gif", "/static/face/f61.gif", "/static/face/f62.gif", "/static/face/f63.gif",
		"/static/face/f64.gif", "/static/face/f65.gif", "/static/face/f66.gif", "/static/face/f67.gif",
		"/static/face/f68.gif", "/static/face/f69.gif",
		"/static/face/f70.gif", "/static/face/f71.gif"
	],
	faceFlag: false,
	faceTemp: {},
	noticeTemp: [],
	connectSocketInit(url, key, globalUserId, limitFlag) {
		let that = this;
		that.websokect = uni.connectSocket({
			url: url,
			protocols: [key],
			complete() {
				that.globalUserId = globalUserId;
				that.limitFlag = limitFlag;
			}
		});

		that.websokect.onOpen((e) => {
			that.soketCallBack();
		});
	},

	soketCallBack() {
		let that = this;
		that.websokect.onMessage((res) => {
			let jsonObject = JSON.parse(res.data);
			console.log("onSocketMessage------", jsonObject);
			let command = jsonObject.command;
			let code = jsonObject.code;
			if (command === 11) { //接收到聊天响应处理;
				that.COMMAND_CHAT_RESP(jsonObject);
			} else if (command === 18) { //获取用户信息响应处理;
				that.COMMAND_GET_USER_RESP(jsonObject);
			} else if (10000 === code && command === 12) { //聊天发送状态;
				//COMMAND_CHAT_RESP_SEND_STATUS(data);
			} else if (command === 9) { //加入群组的消息通知处理;
				that.COMMAND_JOIN_GROUP_NOTIFY_RESP(jsonObject);
			} else if (command === 10) {
				//COMMAND_EXIT_GROUP_NOTIFY_RESP(dataObj);
			} else if (command === 20 && code === 10015) {

			} else if (command === 20 && code === 10016) { //处理离线消息;
				var msgFlag = "离线消息";
				that.COMMAND_GET_OFF_MESSAGE_RESP(jsonObject);
			} else if (command === 20 && code === 10018) { //处理历史消息;
				var msgFlag = "历史消息";

			} else if (command === 6) { //登陆命令返回状态处理
				if (code === 10007) {
					that.COMMAND_LOGIN_RESP();
				}
			} else {

			}
		});
	},
	COMMAND_LOGIN_RESP() {
		let that = this;
		//获取登录用户信息;	
		var userCmd = JSON.stringify({
			cmd: 17,
			type: '2',
			userId: that.globalUserId
		});

		that.websokect.send({
			data: userCmd,
			success: function() {

			},
			fail: function() {
				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '数据发送失败'
				});
			}
		});

		//1.离线消息
		//获取用户离线消息(好友+群组);
		var msgCmd = JSON.stringify({
			cmd: 19,
			type: '0',
			userId: that.globalUserId
		});

		that.websokect.send({
			data: msgCmd,
			success: (res) => {

			},
			fail: (e) => {

			}
		});
	},
	//加入群组的消息通知处理;
	COMMAND_JOIN_GROUP_NOTIFY_RESP(data) {
		var that = this;
		var user = data.user;
		if (user.adminUuid && user.adminUuid === that.globalUserId) {
			if (user.userId != that.globalUserId) {
				var index = that.listKey.indexOf(user.userId);
				if (index > -1) {
					var userIndex = that.noticeTemp.indexOf(user.userId);
					var tempUserInfo = that.list[userIndex];
					var offlineCount = tempUserInfo.offlineCount + 1;
					user.offlineCount = offlineCount;


					that.list.splice(userIndex, 1);
					that.list.push({ ...user
					});

					that.noticeTemp.splice(userIndex, 1);
					that.noticeTemp.push(user.userId);
				} else {
					that.listKey.push(user.userId);
					user.createTime = that.happenTimeFun(new Date().getTime());
					user.notiyTime = that.formatDate(new Date(), 'hh:mm');
					user.mes = '通过应用【' + user.applicationName + '】中的产品【' + user.productName + '】发起聊天...';
					user.mesType = 0;
					user.offlineCount = 1;
					that.list.push({ ...user
					});
					that.noticeTemp.push(user.userId);
				}
			}
		}
	},
	//获取用户信息响应处理;
	COMMAND_GET_USER_RESP(data) {
		var user = data.data;
		this.curUser = user;
	},
	//接收到聊天响应处理;
	COMMAND_CHAT_RESP(data) {
		var chatObj = data.data;
		console.log("COMMAND_CHAT_RESP----------", chatObj)
		var from = chatObj.from;
		if (from === this.globalUserId)
			return;
		var content = chatObj.content;
		var user = this.getOnlineUserById(from);
		var globalUser = this.getOnlineUserById(this.globalUserId);
		var ownUser = globalUser;
		var friendUser = user;

		//2.接收到的消息
		//组装数据
		let chatContent = {};
		if (friendUser) {
			chatContent = friendUser;
			chatContent.mine = false;
		} else {
			chatContent = ownUser;
			chatContent.mine = true;
		}

		var mesType = this.getContentType(content);
		content = this.replaceLayHtml(content);
		chatContent.mesType = mesType;
		chatContent.mes = content;
		chatContent.createTime = this.happenTimeFun(chatObj.createTime);
		chatContent.notiyTime = this.formatDate(new Date(), 'hh:mm');
		chatContent.off = false;
		if (chatContent) {
			this.chatMessage.push({ ...chatContent
			});
		}

		if (friendUser) {
			var index = this.listKey.indexOf(friendUser.userId);
			if (index > -1) {
				var userIndex = this.noticeTemp.indexOf(friendUser.userId);
				var tempUserInfo = this.list[userIndex];
				console.log("----------", tempUserInfo)
				var offlineCount = tempUserInfo.offlineCount + 1;
				friendUser.offlineCount = offlineCount;


				this.list.splice(userIndex, 1);
				this.list.push({ ...friendUser
				});

				this.noticeTemp.splice(userIndex, 1);
				this.noticeTemp.push(friendUser.userId);
			} else {
				friendUser.offlineCount = 1;
				friendUser.mes = chatContent.mes;
				friendUser.notiyTime = chatContent.notiyTime;
				this.listKey.push(friendUser.userId);
				this.list.push(friendUser);
				this.noticeTemp.push(friendUser.userId);
			}
		}
	},

	//处理用户离线消息
	COMMAND_GET_OFF_MESSAGE_RESP(data) {
		console.log("COMMAND_GET_OFF_MESSAGE_RESP", data)
		var msgObj = data.data;
		var friends = msgObj.friends;
		var offlineMessage = this.offlineMessage = friends;
		if (offlineMessage) {
			for (var key in offlineMessage) {
				var chatDatas = offlineMessage[key];
				var offlineCount = 0;
				var applicationName, productName, nick, avatar, userId;
				for (var index in chatDatas) {
					var user_id = chatDatas[index].from;
					var content = chatDatas[index].content;
					var userInfo = this.getOnlineUserById(user_id);
					userInfo.mine = false;
					userInfo.createTime = this.happenTimeFun(chatDatas[index].createTime);
					var mesType = this.getContentType(content);
					content = this.replaceLayHtml(content);
					userInfo.mesType = mesType;
					userInfo.mes = content;
					userInfo.off = true;

					applicationName = userInfo.applicationName;
					productName = userInfo.productName;
					nick = userInfo.nick;
					avatar = userInfo.avatar;
					userId = user_id;

					var index = this.listKey.indexOf(user_id);
					if (index > -1) {
						offlineCount += 1;
					} else {
						offlineCount = 1;
						this.listKey.push(user_id);
					}

					this.chatMessage.push({ ...userInfo
					});
				}

				var user = {};
				user.userId = userId;
				user.nick = nick;
				user.avatar = avatar;
				user.createTime = this.happenTimeFun(new Date().getTime());
				user.notiyTime = this.formatDate(new Date(), 'hh:mm');
				user.mes = '通过应用【' + applicationName + '】中的产品【' + productName + '】发起聊天...【离线消息】';
				user.mesType = 0;
				user.offlineCount = offlineCount;

				var index = this.listKey.indexOf(userId);
				if (index > -1) {
					var userIndex = this.noticeTemp.indexOf(userId);
					var tempUserInfo = this.list[userIndex];
					var myOfflineCount = tempUserInfo.offlineCount + offlineCount;
					user.offlineCount = myOfflineCount;

					this.list.splice(userIndex, 1);
					this.list.push({ ...user
					});

					this.noticeTemp.splice(userIndex, 1);
					this.noticeTemp.push(userId);

				} else {
					this.list.push({ ...user
					});
					this.noticeTemp.push(userId);
				}

			}
		}
	},

	//获取指定用户信息
	getOnlineUserById(id) {
		var groups = this.curUser.groups;
		//console.log("getOnlineUserById--------", groups)
		var onlineUserStr = "";
		for (var g = 0; g < groups.length; g++) {
			var group = groups[g];
			var users = group.users;
			for (var u = 0; u < users.length; u++) {
				var user = users[u];
				if (user.userId === id) {
					return user;
				}
			}
		}
	},

	//时间戳数据处理
	happenTimeFun(num) {
		let date = new Date(num);
		return this.formatDate(date, 'yyyy-MM-dd hh:mm:ss');
	},
	formatDate(date, fmt) {
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
		}

		let o = {
			'M+': date.getMonth() + 1,
			'd+': date.getDate(),
			'h+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds()
		};
		for (let k in o) {
			if (new RegExp(`(${k})`).test(fmt)) {
				let str = o[k] + '';
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
			}
		}
		return fmt;
	},
	padLeftZero(str) {
		return ('00' + str).substr(str.length);
	},
	replaceLayHtml(content) {
		var that = this;
		content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
			.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
			.replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@

			.replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
				var alt = face.replace(/^face/g, '');
				return that.faceTemp[alt];
			})
			.replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
				return img.replace(/(^img\[)|(\]$)/g, '');
			})
			.replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
				var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
				var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
				if (!href) return str;
				return href;

			})
			.replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
				return audio.replace(/(^audio\[)|(\]$)/g, '');
			})
			.replace(/video\[([^\s]+?)\]/g, function(video) { //转义视频
				return video.replace(/(^video\[)|(\]$)/g, '');
			})

			.replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义链接
				var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
				var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
				if (!href) return str;
				return href;
			});
		return content;
	},
	faces(index) {
		if (!this.faceFlag) {
			for (var j = 0, len = this.originFace.length; j < len; j++) {
				this.faceTemp[this.originFace[j]] = this.faceList[j] = "/static/face/f" + j + ".gif";
			}
			this.faceFlag = true;
		}
		return this.faceTemp[index];
	},
	getContentType(content) {

		if (null != content.match(/face\[([^\s\[\]]+?)\]/g)) {
			//表情
			return 1;
		} else if (null != content.match(/img\[([^\s]+?)\]/g)) {
			//图片
			return 2;
		}
		return 0;
	}
}
